package com.xuyl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuyl.constant.MessageCode;
import com.xuyl.constant.MessageConstant;
import com.xuyl.dao.UserDao;
import com.xuyl.domain.User;
import com.xuyl.entity.QueryBean;
import com.xuyl.exception.BusinessException;
import com.xuyl.exception.SystemException;
import com.xuyl.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.context.Theme;

import java.util.List;
import java.util.Objects;

/**
 * @author nisemono
 * @date 2023-02-27 19:19
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;


    @Override
    public boolean save(User user) {
        if (Objects.isNull(user)) {
            throw new SystemException(MessageCode.SAVE_ERR, MessageConstant.EMPTY_DATA_ERR);
        }
        // 数据校验
        if (user.getName() == null || Objects.equals(user.getName(), "")) {
            throw new BusinessException(MessageCode.SAVE_ERR, "名称不可以为空");
        }

        if (user.getPhone() == null || Objects.equals(user.getPhone(), "")) {
            throw new BusinessException(MessageCode.SAVE_ERR, "电话不可以为空");
        }

        // 添加
        return userDao.insert(user) > 0;
    }

    @Override
    public boolean updateUserInfoById(User user) {
        // 检查是否为无效数据
        this.checkInvalidData(user);

        // 检查乐观锁的值
        boolean isSys = this.checkVersion(user);

        return userDao.updateById(user) > 0;
    }

    @Override
    public boolean deleteById(Integer id) {
        this.checkIdIsNull(id);
        return userDao.deleteById(id) > 0;
    }

    @Override
    public boolean deleteBatch(List<Integer> ids) {
        if (ids == null || ids.size() <= 0) {
            throw new BusinessException(MessageCode.DELETE_ERR, MessageConstant.EMPTY_DATA_ERR);
        }

        for (Integer id : ids) {
            this.deleteById(id);
        }
        return true;
    }

    @Override
    public User getUserById(Integer id) {
        this.checkIdIsNull(id);
        return userDao.selectById(id);
    }


    @Override
    public IPage<User> getUserInfoPage(QueryBean queryBean) {
        if (queryBean.getCurrentPage() == null || queryBean.getPageSize() == null) {
            throw new SystemException(MessageCode.GET_ERR, MessageConstant.QUERY_USER_SUCCESS);
        }
        IPage<User> page = new Page<>(queryBean.getCurrentPage(), queryBean.getPageSize());
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        // 关键字查询，使用MP携带的查询类拼接sql语句
        if (queryBean.getQueryString() == null || "".equals(queryBean.getQueryString())) {
            lqw = null;
        } else {
            // 根据性别查询
            String val = queryBean.getQueryString();
            if (Objects.equals(val, "女")) {
                lqw.eq(User::getSex, 1);
            } else if (Objects.equals(val, "男")) {
                lqw.eq(User::getSex, 0);
            } else {
                // 更具地址，姓名，手机号，性别模糊查询
                lqw.like(User::getName, val)
                        .or().like(User::getProvince, val)
                        .or().like(User::getCity, val)
                        .or().like(User::getCounty, val)
                        .or().like(User::getAddress, val)
                        .or().like(User::getSex, val)
                        .or().like(User::getPhone, val);

            }

        }
        return userDao.selectPage(page, lqw);
    }

    @Override
    public boolean updateDeletedUserInfoById(Integer id) {
        return userDao.updateDeletedById(id) > 0;
    }

    @Override
    public List<User> getAll() {
        List<User> users = userDao.selectList(null);
        return users;
    }


    private boolean checkIdIsNull(Integer id) {
        if (id == null) {
            throw new SystemException(MessageCode.DELETE_ERR, MessageConstant.DELETE_USER_FAILED);
        }
        return true;
    }


    /**
     * 检查乐观锁
     *
     * @param user
     * @return
     */
    private boolean checkVersion(User user) {
        User user2 = userDao.selectById(user.getId());
        if (!user2.getVersion().equals(user.getVersion())) {
            // 乐观锁不匹配
            throw new BusinessException(MessageCode.VERSION_ERR, MessageConstant.DATA_SYNCHRONIZATION_FAILED);
        }
        return true;
    }

    private boolean checkInvalidData(User user) {
        User user2 = userDao.selectById(user.getId());
        if (user2.getDeleted() == 1) {
            // 数据已经删除
            throw new BusinessException(MessageCode.BUSINESS_ERR, MessageConstant.REPEAT_DELETED_FAILED);
        }
        return true;
    }
}
